// 正确的导入方式
import axios, { type AxiosResponse } from 'axios';

export interface EnsembleTrainParams {
    target_col?: string;
    horizon?: number;
}

export interface EnsembleTrainResponse {
    status: 'success' | 'error';
    message?: string;
    target_column?: string;
    horizon?: number;
    model_dir?: string;
    timestamp?: string;
    traceback?: string;
}

export interface EnsembleModelStatus {
    target_col?: string;
}

export interface EnsembleStatusResponse {
    status: 'success' | 'error' | 'not_trained' | 'not_trained_in_{model_dir}';
    models?: Array<{
        target_column: string;
        day: number;
        file: string;
        last_modified: string;
    }>;
    available_targets?: string[];
    max_horizon?: number;
    model_count?: number;
    message?: string;
}

/**
 * 训练集成学习模型
 * @param params 训练参数
 * @returns 训练结果
 */
export const trainEnsembleModel = async (
    params: EnsembleTrainParams
): Promise<EnsembleTrainResponse> => {
    try {
        const response: AxiosResponse<EnsembleTrainResponse> = await axios.get(
            'http://127.0.0.1:5000/api/train_ensemble',
            {
                params: {
                    target_col: params.target_col || 'guilin_max',
                    horizon: params.horizon || 7,
                },
            }
        );

        return response.data;
    } catch (error) {
        if (axios.isAxiosError(error) && error.response) {
            return error.response.data;
        }
        return {
            status: 'error',
            message: '请求失败，请检查网络连接',
        };
    }
};

/**
 * 获取集成学习模型训练状态
 * @param params 查询参数
 * @returns 模型状态信息
 */
export const getEnsembleModelStatus = async (
    params: EnsembleModelStatus
): Promise<EnsembleStatusResponse> => {
    try {
        const response: AxiosResponse<EnsembleStatusResponse> = await axios.get(
            '/train_ensemble_status',
            {
                params: {
                    target_col: params.target_col,
                },
            }
        );

        return response.data;
    } catch (error) {
        if (axios.isAxiosError(error) && error.response) {
            return error.response.data;
        }
        return {
            status: 'error',
            message: '请求失败，请检查网络连接',
        };
    }
};